package com.unitd.base.frame.spring.editor;

import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;

import java.beans.PropertyEditorSupport;

/**
 * 用于处理前台传送的特殊字符串, 防止XSS攻击
 *
 * @author Hudan
 * @version 1.0
 * @filename MD5Utils.java
 * @copyright www.unitd.com
 * @date 2019-01-25
 */
public class StringEscapeEditor extends PropertyEditorSupport {

    /** 编码HTML */
    private boolean escapeJavaScript;
    /** 编码javascript */
    private boolean escapeHTML;

    /**
     * 构造方法
     */
    public StringEscapeEditor() {
    }

    /**
     * 构造方法
     *
     * @param escapeHTML       需要进行转义的html串
     * @param escapeJavaScript 专业规则脚本
     */
    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) {
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
    }

    /**
     * 处理需要转义的字符串文本
     *
     * @param text 时间值
     */
    @Override
    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            if (escapeHTML) {
                value = HtmlUtils.htmlEscape(value);
            }
            if (escapeJavaScript) {
                value = JavaScriptUtils.javaScriptEscape(value);
            }
            setValue(value);
        }
    }

    /**
     * 获取转义后的字符串文本
     *
     * @return 转义后的字符串
     */
    @Override
    public String getAsText() {
        Object value = getValue();
        return value != null ? value.toString() : "";
    }
}